import { Component, OnInit } from '@angular/core';
import { Router }  from '@angular/router';
import { HttpRequest } from "../../service/httpRequest";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  isLogin:any;
  public authError:any;
  constructor( private _router:Router,private httpRequest:HttpRequest){}
  user:any = {"username":"","password":""};

  ngOnInit(){
    this.isLogin = JSON.parse(localStorage.getItem("isLogin"));
    if(this.isLogin != null && this.isLogin != undefined){
      this._router.navigate(['/page','']);
    }
  }


  login(){
    this.httpRequest.sendPost('account/login',this.user,'op').subscribe(res=>{
      //console.log(res)
      if(res.resultStatus == 200){
        localStorage.setItem("isLogin",'true');
        localStorage.setItem("token",res.result.token);
        //console.log(res.result.token)
        localStorage.setItem("account",JSON.stringify(res.result.account));
        let menus = [];
        //console.log(res.result)
        res.result.menus.forEach(el=>{
          menus.push(el.name);
        });
        localStorage.setItem("menus",JSON.stringify(menus));
        this._router.navigateByUrl('/page');
      }else{
        this.authError = 'username or password error';
        console.log(this.authError);
      }
    },err=>console.log(err));
   
  }





}
